package org.university.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.university.common.Constant;

import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Properties;

public class PasswordUtil {

    private static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 生成加密后的密码
     */
    public static String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 验证密码是否正确
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 生成随机密码（用于重置密码场景）
     */
    public static String generateRandomPassword(int length) {
        String chars = Constant.getChars();
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 从 application.properties 文件中获取密钥 secret_key
     * @return 密钥字符串
     * @throws IOException 如果文件读取失败
     */
    public static String getSecretKey() throws IOException {
        // 使用 PasswordUtil.class.getClassLoader() 获取 ClassLoader
        InputStream inputStream = PasswordUtil.class.getClassLoader().getResourceAsStream("application.properties");
        if (inputStream == null) {
            throw new IOException("无法找到 application.properties 文件");
        }
        Properties properties = new Properties();
        properties.load(inputStream);
        inputStream.close(); // 记得关闭流
        return properties.getProperty("secret_key");
    }
}